<script setup>
import {onMounted, onUnmounted, ref, reactive, unref} from "vue";
import {httpGet, httpPost} from "@/utils/http.js";
import {ElMessage} from "element-plus";
import {dateFormat, removeArrayItem, substr} from "@/utils/libs.js";
import {DocumentCopy, Plus, ShoppingCart, Search} from "@element-plus/icons-vue";
import ClipboardJS from "clipboard";

const items = ref([])
const query = ref({type: ''})
const item = ref({})

const showDialog = ref(false)
const rules = reactive({
  name: [{required: true, message: "请输入名称", trigger: "change"}],
  type: [{required: true, message: "请选择用途", trigger: "change"}],
  value: [{required: true, message: "请输入 API KEY 值", trigger: "change"}],
});

const loading = ref(true)
const formRef = ref(null)
const title = ref('')
const types = ref([
  {label: '对话', value: 'chat'},
  {label: "Midjourney", value: "mj"},
  {label: "Stable-Diffusion", value: "sd"},
  {label: "DALL-E", value: "dalle"},
  {label: "Suno文生歌", value: "suno"},
  {label: "Luma视频", value: "luma"},
  {label: "Realtime API", value: "realtime"},
])

const isEdit = ref(false)
const clipboard = ref(null)
const presets = ref([
  {label: "GiteeAI", value: "https://ai.gitee.com"},
  {label: "中转01", value: "https://api.geekai.pro"},
  {label: "中转03", value: "https://api.geekai.me"},
  {label: "OpenAI", value: "https://api.openai.com"},
]);
const preset = ref(null);

onMounted(() => {
  clipboard.value = new ClipboardJS('.copy-key')
  clipboard.value.on('success', () => {
    ElMessage.success('复制成功！')
  })

  clipboard.value.on('error', () => {
    ElMessage.error('复制失败！')
  })
  // 查询列表数据
  fetchData()
})

onUnmounted(() => {
  clipboard.value.destroy()
})

// 根据类型获取名称
const getTypeName = (type) => {
  for (let v of types.value) {
    if (v.value === type) {
      return v.label
    }
  }
  return ""
}

// 获取列表数据
const fetchData = () => {
  httpGet('/api/admin/apikey/list', query.value).then(res => {
    if (res.data) {
      // 初始化数据
      const arr = res.data
      // 把时间字段进行格式化
      for (let i = 0; i < arr.length; i++) {
        arr[i].last_used_at = dateFormat(arr[i].last_used_at)
      }
      items.value = arr
    }
    loading.value = false
  }).catch(e => {
    ElMessage.error('获取数据失败')
  })
}

// 点击新增时触发
const add = () => {
  showDialog.value = true
  title.value = '新增 API KEY'
  isEdit.value = false
  item.value = {
    enabled: true,
    api_url: "",
  };
}

// 点击编辑时触发
const edit = (row) => {
  showDialog.value = true
  title.value = '修改 API KEY'
  item.value = row
  isEdit.value = true
}

// 新增
const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      showDialog.value = false
      httpPost('api/admin/apikey/saveOrUpdate', item.value).then(res => {
        ElMessage.success('操作成功！')
        // 判断 item 中是否包含 id 字段，如果包含就是修改，不包含就是新增
        if (!item.value['id']) {
          const newItem = res.data
          // 格式化日期
          newItem.last_used_at = dateFormat(newItem.last_used_at)
          items.value.push(newItem)
        }
        fetchData()
      }).catch(e => {
        ElMessage.error('操作失败：' + e.message)
      })
    } else {
      return false
    }
  })
}

// 删除
const remove = (row) => {
  httpGet('/api/admin/apikey/remove?id=' + row.id).then(() => {
    ElMessage.success('删除成功！')
    // 删除集合中的元素
    items.value = removeArrayItem(items.value, row, (v1, v2) => {
      return v1.id === v2.id
    })
  }).catch(e => {
    ElMessage.error('删除失败：' + e.message)
  })
}

// 启用/禁用
const set = (filed, row) => {
  httpPost('/api/admin/apikey/set', {id: row.id, filed: filed, value: row[filed]}).then(() => {
    ElMessage.success('操作成功！')
  }).catch(e => {
    ElMessage.error('操作失败：' + e.message)
  })
}

const changePreset = (row) => {
  item.value.api_url = row.value
  if (!item.value.name) {
    item.value.name = row.label
  }
}

// 关闭弹框触发
const closeDialogCall = () => {
  resetForm()
  item.value = {enabled: true, api_url: ''}
}

// 重置表单
const resetForm = () => {
  if (!formRef) {
    return
  }
  const form = unref(formRef)
  form.resetFields()
}


const clearSearchSelect = () => {
  fetchData()
}

</script>


<template>
  <div class="container list" v-loading="loading">
    <div class="handle-box">
      <el-select v-model="query.type" @clear="clearSearchSelect" clearable placeholder="类型" class="handle-input">
        <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value"/>
      </el-select>

      <el-button :icon="Search" @click="fetchData">搜索</el-button>
      <el-button type="primary" :icon="Plus" @click="add">新增</el-button>
      <a href="https://api.geekai.pro" target="_blank" style="margin-left: 10px">
        <el-button type="success" :icon="ShoppingCart" @click="add" plain>购买API-KEY</el-button>
      </a>
    </div>
    <el-row>
      <el-table :data="items" :row-key="row => row.id" table-layout="auto">
        <el-table-column prop="name" label="名称"/>
        <el-table-column prop="value" label="API KEY">
          <template #default="scope">
            <span>{{ substr(scope.row.value, 20) }}</span>
            <el-icon class="copy-key" :data-clipboard-text="scope.row.value">
              <DocumentCopy/>
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="api_url" label="API URL">
          <template #default="scope">
            <span>{{ substr(scope.row.api_url, 30) }}</span>
            <el-icon class="copy-key" :data-clipboard-text="scope.row.api_url">
              <DocumentCopy/>
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型">
          <template #default="scope">
            {{ getTypeName(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="proxy_url" label="代理地址"/>
        <el-table-column label="最后使用时间">
          <template #default="scope">
            <span v-if="scope.row['last_used_at']">{{ scope.row['last_used_at'] }}</span>
            <el-tag v-else>未使用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="启用状态">
          <template #default="scope">
            <el-switch v-model="scope.row['enabled']" @change="set('enabled',scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-popconfirm title="确定要删除当前记录吗？" @confirm="remove(scope.row)" :width="200">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <el-dialog @close="closeDialogCall" v-model="showDialog" :close-on-click-modal="false" :title="title">
      <el-form :model="item" label-width="120px" ref="formRef" :rules="rules">
        <el-form-item label="名称：" prop="name">
          <template #default>
            <el-row :gutter="10" class="w-full">
              <el-col :span="12">
                <el-input v-model="item.name" autocomplete="off"/>
              </el-col>
              <el-col :span="12">
                <el-select v-model="preset" placeholder="请选择预设" @change="changePreset">
                  <el-option v-for="item in presets" :value="item" :label="item.label" :key="item.value">{{item.label}}</el-option>
                </el-select>
              </el-col>
            </el-row>
          </template>
        </el-form-item>
        <el-form-item label="类型：" prop="type">
          <el-select v-model="item.type" placeholder="请选择类型">
            <el-option v-for="item in types" :value="item.value" :label="item.label" :key="item.value">
              {{ item.label }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="API KEY：" prop="value">
          <el-input v-model="item.value" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="API URL：" prop="api_url">
          <el-input v-model="item.api_url" autocomplete="off"
                    placeholder="只填 BASE URL 即可，如：https://api.openai.com 或者 wss://api.openai.com"/>
        </el-form-item>
        <el-form-item label="启用状态：" prop="enable">
          <el-switch v-model="item.enabled"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="save">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="stylus">
.list {
  .handle-box {
    margin-bottom 20px

    .handle-input {
      max-width 150px;
      margin-right 10px;
    }
  }

  .copy-key {
    margin-left 5px
    cursor pointer
  }

  .el-select {
    width: 100%
  }

  .pagination {
    padding 20px 0
    display flex
    justify-content righ
  }
}

.el-form {
  .el-form-item__content {
    .info {
      color #999999
    }

    .el-icon {
      padding-left: 10px;
    }
  }
}
</style>